#include "EventLoopThread.h"
#include "EventLoop.h"

EventLoopThread::EventLoopThread(const ThreadInitCallback &cb, const std::string& name)
    : loop_(nullptr), thread_(std::bind(&EventLoopThread::threadFunc, this), name), exiting_(false), mutex_(), cond_(), callback_(cb)
{
}
EventLoopThread ::~EventLoopThread()
{
    exiting_ = true;
    if (loop_ != nullptr)
    {
        loop_->quit();
        thread_.join();
    }
}

EventLoop *EventLoopThread::startLoop()
{
    thread_.start(); // 启动线程
    EventLoop *loop = nullptr;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while (loop_ == nullptr) // 等待thread创建eventloop
        {
            cond_.wait(lock);
        }
        loop = loop_;
    }
    return loop; // 给外部返回创建的loop
}

void EventLoopThread::threadFunc()
{
    EventLoop loop; // 线程栈EventLoop-one loop per thread
    if (callback_)  // 线程初始化
    {
        callback_(&loop);
    }
    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop; // eventloopthread 获取线程创建的 loop
        cond_.notify_one();
    }
    loop.loop(); // eventloop 进行IO复用
    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = nullptr;
    }
}